{include file="public/header" /}
<link rel="stylesheet" type="text/css" href="{ STATIC }/css/editor.css" />
</head>
<body>
  <div id="web-container">
    <div class="editor-header">
      <div class="editor-header-content">
        <div class="logo">
          <a href="/index.html">
            <img src="https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/6bdafd801c878b10edb5fed5d00969e9.svg" alt="掘粪">
            <span>掘粪</span>
          </a>
        </div>
        <div class="user-info">
          <span>文章将自动保存至草稿箱</span>
          <a href="/index.html" type="button" class="btn btn-warning">草稿箱</a>
          <button class="btn btn-primary" id="publish-btn">发布</button>
        </div>
      </div>
    </div>
    <div class="editor-container">
      <input type="textarea" id="editor-title" placeholder="请输入文章标题（5～30个字）" autocomplete="off" value="" onkeyup="value=value.replace(/[ ~`$]/, '')"></input>
      <div id="editor"></div>
      <textarea id="editor-summary" placeholder="请输入文章摘要（5～30个字）" autocomplete="off" value="" onkeyup="value=value.replace(/[ ~`$]/, '')"></textarea>
    </div>
  </div>
</body>
{include file="public/footer" /}
<script type="text/javascript" src="{ STATIC }/js/wangEditor.min.js"></script>
<script>
  $(function () {
      $('#editor-title').on('keyup', (_.debounce(function () {
        uploadEditor()
      }, 2000)));
      $('#editor-summary').on('keyup', (_.debounce(function () {
        uploadEditor()
      }, 2000)));
      const Editor = window.wangEditor
      const editor = new Editor('#editor')
      // 设置编辑区域高度为 500px
      editor.config.height = 600
      let editorHtml = ''
      let articleId = null
      let contentId = null
      editor.config.onchange = _.debounce(function (newHtml) {
        editorHtml = newHtml
        uploadEditor()
      }, 2000);
      // 配置触发 onchange 的时间频率，默认为 200ms
      editor.config.onchangeTimeout = 2000; // 修改为 2000ms
      // 插入网络图片的回调
      // editor.config.linkImgCallback = function (src,alt,href) {
      //   console.log('图片 src ', src)
      //   console.log('图片文字说明',alt)
      //   console.log('跳转链接',href)
      // }
      // 自行上传图片
      editor.config.customUploadImg = function (resultFiles, insertImgFn) {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        // 上传图片，返回结果，将图片插入到编辑器中
        const file = resultFiles[0]
        if (file.type !== 'image/jpeg') return false
        if (file.size > 1024 * 1024) return false
        const formData = new FormData()
        formData.append('pic', file)
        $.ajax({
          url: '/admin/upload/pic',
          method: 'post',
          cache: false,
          processData: false,
          contentType: false,
          data: formData,
          success: function(res) {
            if (res.status === 200) {
              insertImgFn(res.data)
            }
          }
        })
      }
      editor.create()
      // 保存草稿
      function uploadEditor () {
        const coverImage = $('#editor img')[0];
        if (articleId) {
          const data = {
            articleId: articleId,
            contentId: contentId,
            title: $('#editor-title').val(),
            content: editorHtml,
            summary: $('#editor-summary').val(),
            coverImage: coverImage ? coverImage.src : '',
            status: 0
          }
          $.ajax({
            url: '/index/editor/update',
            method: 'post',
            data,
            success: function(res) {
              if (res.status !== 200) {
                $('#alert').text(res.msg).addClass('in')
                setTimeout(() => {
                  $('#alert').removeClass('in')
                }, 1000);
              }
            }
          })
        } else {
          const data = {
            title: $('#editor-title').val(),
            content: editorHtml,
            summary: $('#editor-summary').val(),
            coverImage: coverImage ? coverImage.src : ''
          }
          $.ajax({
            url: '/index/editor/create',
            method: 'post',
            data,
            success: function(res) {
              if (res.status === 200) {
                articleId = res.data.article_id
                contentId = res.data.content_id
              }
            }
          })
        }
      }
      // 发布
      $('#publish-btn').click(function () {
        if (!articleId) return false
        const coverImage = $('#editor img')[0];
        const data = {
            articleId: articleId,
            contentId: contentId,
            title: $('#editor-title').val(),
            content: editorHtml,
            summary: $('#editor-summary').val(),
            coverImage: coverImage ? coverImage.src : '',
            status: 1
          }
          $.ajax({
            url: '/index/editor/update',
            method: 'post',
            data,
            success: function(res) {
              if (res.status !== 200) {
                $('#alert').text(res.msg).addClass('in')
                setTimeout(() => {
                  $('#alert').removeClass('in')
                }, 2000);
              } else {
                window.location.href = '/index'
              }
            }
          })
      })
    }
  )
</script>
</html>